
package com.parttimetask.utils;

import org.json.JSONObject;

import java.io.File;
import java.util.concurrent.TimeUnit;

import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class Http {
    public static final String BASE_URL = "http://39.109.117.81/";
//    public static final String BASE_URL = "http://192.168.3.86/";
    public static Request.Builder getBuilder(String url){
        return new Request.Builder().url(url).addHeader("Content-Type","application/json").addHeader("Access-Control-Allow-Origin","*");
    }
    public static OkHttpClient getClient(){
        return new OkHttpClient.Builder().readTimeout(5000, TimeUnit.SECONDS).connectTimeout(5000, TimeUnit.SECONDS).writeTimeout(5000,TimeUnit.SECONDS).build();
    }
    public static void get(String url, Callback callback){
        getClient().newCall(getBuilder(BASE_URL+url).build()).enqueue(callback);
    }
    public static void post(JSONObject jsonObject,String url,Callback callback){
        getClient().newCall(getBuilder(BASE_URL+url).post(RequestBody.create(MediaType.parse("application/json;charset=utf-8"), String.valueOf(jsonObject))).build()).enqueue(callback);
    }
    public static Request.Builder getFileBuilder(String url){
        return new Request.Builder().url(url);
    }
    public static void upload(String url, File file, Callback callback){
        getClient().newCall(getFileBuilder(BASE_URL+url).post(new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file)).build()).build()).enqueue(callback);
    }
}